#include "circle.h"
#include <stdlib.h>
#include <stdio.h>

int init_circle(LinkedList l)
{
	l->head = 0;
	l->size = 0;
	return 0;
}

int insert_circle(LinkedList l, int element, int pos) 
{
	if (pos > l->size)
	{
		return -1;
	}
	LinkedNode new_node = malloc(sizeof(struct linkednode));
	if (!new_node)
	{
		return -1;
	}
	new_node->element = element;
	if (pos == 0) 
	{
		LinkedNode old_head = l->head;
		l->head = new_node;
		if (l->size == 0)
		{
			new_node->next = l->head;
			l->size++;
			return 0;
		}
		
		LinkedNode tail = old_head->next;
		while (tail->next != old_head)
		{
			tail = tail->next;
		}

		tail->next = l->head;
		l->size++;
		return 0;
	}

	LinkedNode p = l->head;
	int i = 0;
	while(++i < pos)
	{
		p = p->next;
	}
	new_node->next = p->next;
	p->next = new_node;
	l->size++;
	return 0;
}

int insert_circle_tail(LinkedList l, int element)
{
	return insert_circle(l, element, l->size);
}

int remove_next(LinkedList l, LinkedNode node)
{
	if (l -> size == 0)
	{
		return -1;
	}
	// 删除头节点特殊处理
	if (node->next == l->head)
	{
		l->head = node->next->next;
	}
	LinkedNode p = node->next;
	node->next = p->next;
	l->size--;
	free(p);
	return 0;
}

void print(LinkedList l)
{
	LinkedNode head = l->head;
	LinkedNode p = head;
	printf("[%d ", p->element);
	while (p->next != head)
	{
		p = p->next;
		printf("%d ", p->element);
	}
	printf("]\n");
}
